package 纯编程题配套习题;

import org.junit.Assert;

/**
 * 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。
 *
 * 比如，输入字符串"abcdefg"和数字2，该函数将返回左旋转两位得到的结果"cdefgab"。
 *
 * 示例 1：
 * 输入: s = "abcdefg", k = 2
 * 输出:"cdefgab"
 *
 * 示例 2：
 * 输入: s = "lrloseumgh", k = 6
 * 输出:"umghlrlose"
 *
 * 限制：
 * 1 <= k < s.length <= 10000
 *
 * 链接：https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
 */
public class _剑指Offer_58_II_左旋转字符串 {

    public static void main(String[] args) {
        Assert.assertEquals("cdefgab", reverseLeftWords2("abcdefg", 2));
        Assert.assertEquals("umghlrlose", reverseLeftWords2("lrloseumgh", 6));
    }

    public static String reverseLeftWords(String s, int n) {
        char[] charArray = s.toCharArray();
        StringBuilder sb1 = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb1.append(charArray[i]);
        }
        StringBuilder sb2 = new StringBuilder();
        for (int j = n; j < charArray.length; j++) {
            sb2.append(charArray[j]);
        }
        return sb2.toString() + sb1;
    }

    public static String reverseLeftWords2(String s, int n) {
        char[] charArray = s.toCharArray();
        StringBuilder res = new StringBuilder();
        int length = charArray.length;
        for (int i = n; i < length + n; i++) {
            res.append(charArray[i % length]);
        }
        return res.toString();
    }
}
